package com.wholesale;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.wholesale.beans.LoginRequest;
import com.wholesale.beans.LoginResponse;
import com.wholesale.datas.WebServiceClient;
import com.wholesale.utils.Constants;

public class UserLoginLayout extends LinearLayout implements OnClickListener {   
	private ViewFlipper viewFlipper ;
	private Context context ;
	private View baseView ;
	private Button leftButton ;
	private Button rightButton ;
	private TextView headView ;
	
	private RelativeLayout registerLayout ;
	private TextView userNameView ;
	private TextView passwordView ;
	private String userName,password;
	private LoginTask loginTask ;
	//  构造函数  
	public UserLoginLayout(Context context,final ViewFlipper viewFlipper){
		super(context);
		this.viewFlipper = viewFlipper ;
		this.context = context ;
		//加载需要的属性，加载方法一的子Layout  
		baseView = ((Activity) getContext()).getLayoutInflater().inflate(R.layout.userlogin, this);  
		leftButton = (Button)baseView.findViewById(R.id.leftBtn);
		leftButton.setText("Back");
		leftButton.setOnClickListener(this);
		rightButton = (Button)baseView.findViewById(R.id.rightBtn);
		rightButton.setText("Login");
		rightButton.setOnClickListener(this);
		headView = (TextView)baseView.findViewById(R.id.title);
		headView.setText("Login");
		
		userNameView = (TextView)findViewById(R.id.username_text);
        passwordView = (TextView)findViewById(R.id.password_text);
		registerLayout = (RelativeLayout)findViewById(R.id.goregisterLayout);
        registerLayout.setOnClickListener(this);
	}
	
	public void dialog(String title, String message) {
		AlertDialog.Builder builder = new Builder(context);
		builder.setTitle(title);
		builder.setMessage(message);
		builder.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		builder.create().show();
	}
	
	class LoginTask extends AsyncTask<LoginRequest, Integer, LoginResponse>{
		private Context context ;
		ProgressDialog pdialog;
		public LoginTask(Context context){
			this.context = context ;
			pdialog = new ProgressDialog(context);
			pdialog.setTitle("Logining...");
			pdialog.setMessage("Please wait...");
			pdialog.setCancelable(true);
			pdialog.setButton("cancel", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int i) {
					dialog.cancel();
					loginTask.cancel(true);
				}
			});
			pdialog.show();
		}
		@Override
		protected LoginResponse doInBackground(LoginRequest... params) {
			LoginResponse loginResponse = WebServiceClient.login(params[0].toJsonString());
			if(loginResponse != null && loginResponse.getReturnType()==0){
				Constants.loginResponse = loginResponse ;
				Constants.userInfo = WebServiceClient.getUserInfo(loginResponse.getUserId(), loginResponse.getUserToken());
			}
			return  loginResponse;
		}
		@Override
		protected void onPostExecute(LoginResponse result) {
			pdialog.dismiss();
			if(result == null ){
				dialog("Error","Server error!");
			}else{
				if(result.getReturnType() == 1){
					dialog("Error","invilid password!");
				}else if(result.getReturnType() == 2){
					dialog("Error","userId not exist!");
				}else if(result.getReturnType() == 3){
					dialog("Error","Server error!");
				}else{
//					if(viewFlipper.getChildAt(0).getClass().getName().equals(WholeSaleLayout.class.getName())){
//						((WholeSaleLayout)viewFlipper.getChildAt(0)).rightButton.setBackgroundResource(R.drawable.affiche_user_on);
//					}
					Intent myIntent = new Intent();// 创建Intent对象
					myIntent.setAction("com.wholesale.utils.UpdateUIService");
					myIntent.putExtra("cmd", Constants.CMD_LOGIN_SERVICE);
					myIntent.putExtra("from",
							"com.wholesale.UserLoginLayout");
					((Activity) context).sendBroadcast(myIntent);
					viewFlipper.showPrevious();
					viewFlipper.removeView(UserLoginLayout.this);
				}
			}
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}
		
	}
	
	@Override
	public void onClick(View v) {
		InputMethodManager imm = (InputMethodManager)((Activity) getContext()).getSystemService(Context.INPUT_METHOD_SERVICE);  
		switch (v.getId()) {
		case R.id.leftBtn:
			imm.hideSoftInputFromWindow(leftButton.getWindowToken(), 0);
			viewFlipper.showPrevious();
			viewFlipper.removeView(this);
			break;
		case R.id.rightBtn:
			
			imm.hideSoftInputFromWindow(rightButton.getWindowToken(), 0);

			userName = userNameView.getText().toString().trim();
			password = passwordView.getText().toString().trim();
			String message = null;
			if ("".equals(userName)) {
				message = "Please enter the email!";
			}
			if ("".equals(password)) {
				if(message != null){
					message = message +"&password!";
				}else{
					message ="Please enter the password!";
				}
			}
			if(message != null){
				dialog("Login failed",message);
			}else{
				LoginRequest login = new LoginRequest();
				login.setPassword(password);
				login.setUserId(userName);
				loginTask = new LoginTask(context);
				loginTask.execute(login);
			}
			break;
		case R.id.goregisterLayout:
			UserRegisterLayout userRegisterLayout = new UserRegisterLayout(context, viewFlipper);
			viewFlipper.addView(userRegisterLayout);
			viewFlipper.showNext();
			break;
		default:
			break;
		}
	}

	
}
